package com.atguigu.educenter.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.commonutils.vo.OrderUcenterVo;
import com.atguigu.educenter.entity.UcenterMember;
import com.atguigu.educenter.entity.vo.RegisterVo;
import com.atguigu.educenter.service.UcenterMemberService;
import org.apache.http.HttpRequest;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.plaf.SpinnerUI;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author hwt
 * @since 2022-09-18
 */
@RestController
@RequestMapping("/educenter/member")
public class UcenterMemberController {

    @Resource
    private UcenterMemberService ucenterMemberService;

    // 登录接口
    @PostMapping("login")
    public R login(@RequestBody(required = false) UcenterMember ucenterMember) {

        return ucenterMemberService.login(ucenterMember);

    }

    // 注册接口
    @PostMapping("register")
    public R registerUser(@RequestBody RegisterVo registerVo) {
        return ucenterMemberService.register(registerVo);
    }

    // 根据 token 获取到用户信息
    @GetMapping("getMemberInfo")
    public R getTokenInfo(HttpServletRequest request) {
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        UcenterMember byId = ucenterMemberService.getById(memberId);
        return R.ok().data("info", byId);
    }

    // 微服务调用接口，用于根据 token 获取到用户信息
    @GetMapping("/getInfoByToken/{token}")
    public R getInfoByToken(@PathVariable("token") String toKen) {
        String memberId = JwtUtils.getMemberInfoByToken(toKen);

        UcenterMember byId = ucenterMemberService.getById(memberId);

        if (byId == null) return R.error().message("非法用户，请重新登录");

        Map<String, Object> map = new HashMap<>();

        map.put("memberId", byId.getId());

        map.put("avatar", byId.getAvatar());

        map.put("nickname", byId.getNickname());

        return R.ok().data(map);
    }

    // 使用公共的 VO 类，返回用户相关信息
    @GetMapping("getUserInfoOrder/{id}")
    public OrderUcenterVo getUserInfoOrder(@PathVariable("id") String id) {
        UcenterMember byId = ucenterMemberService.getById(id);
        OrderUcenterVo orderUcenterVo = new OrderUcenterVo();
        BeanUtils.copyProperties(byId, orderUcenterVo);

        return orderUcenterVo;
    }

    // 统计指定日期注册的人数
    @GetMapping("countRegister/{day}")
    public R countRegister(@PathVariable("day")String day){
       Integer count = ucenterMemberService.countRegisterDay(day);

       return R.ok().data("count",count);
    }

}











